<?php

namespace App\Http\Middleware;

use App\Common\ErrorCode\ErrorCode;
use App\Exceptions\BusinessException;
use App\Http\Service\JwtService;
use App\Http\Service\UserService;
use Closure;
use Illuminate\Http\Request;
use Lcobucci\JWT\Token;

class WebUidMiddle
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws BusinessException
     */
    public function handle($request, Closure $next)
    {
        $token = $this->getToken($request);
        //$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJtYy5jb20iLCJhdWQiOiJtYy5jb20iLCJqdGkiOiJsXzVkODgzNDhiYzc3MzAxLjE0MDY1ODU3IiwiaWF0IjoxNTY5MjA3NDM1LCJuYmYiOjE1NjkyMTQ2MzUsImV4cCI6MTU2OTIxODIzNSwidWlkIjoyLCJ0eXBlIjoxfQ.sHilDfThuUB_pNgxucokhzugzGpV9a63TeNRB-xBXSKpG7p6GttLrJw5NoBlZ4aStfef-2Hsu-X5yo67r9rm0Eg0HvUQaaMjupsH7YcASnscfoonCJBOth3w_7ej65o8jzP0gkk2XLI_6JHiRJDmKqhbAzg5TUJCIQvU_b-xlsFoSFd3EiufXOOvT_WcAqtptDmQuFF13hznYkNXNlexBBKOtVCcsIbc-bktwNjEP78S5UCz75AnGZTxv-fkPV7udbOXDB206-lSJWH4OMPvlvYsDhbv_FMiPpTLMxAUJ0NdWMkk5dCtkhj3k317zITmENJcdTB6xcTQ24G_VbwqbQ';
        if(!$token){
            $uid = 2;
            $type = 1;

        }else{

            $jwt_token = $this->checkToken($token);

            //保存token
            $uid = $jwt_token->getClaim('uid');
            $type = $jwt_token->getClaim('type');

            UserService::setUserInfo($uid, $type);
        }

        $request->attributes->add(['loginUid'=>2,'loginType'=>1]);
        return $next($request);
    }

    /**
     * 获取token
     * @param Request $request
     * @return array|mixed|string
     * @throws BusinessException
     */
    private function getToken(Request $request)
    {
        $token = $request->cookie('token');
        if (empty($token)) {
            $token = $request->post('token');
        }
        if (empty($token)) {
            $token = $request->get('token');
        }
        return $token;
    }

    /**
     * 校验token
     * @param string $token
     * @return \Lcobucci\JWT\Token|string
     * @throws BusinessException
     */
    private function checkToken(string $token) : Token
    {
        try{
            return JwtService::verify($token);
        }catch (BusinessException $exception) {
            if ($exception->getCode() === ErrorCode::ERROR_JWT_UNABLE_DECODE) {
                throw new BusinessException(ErrorCode::ERROR_TOKEN_INVALID);
            }
        }catch (\Exception $exception) {
            throw new BusinessException(ErrorCode::ERROR_SERVER_UNKNOWN);
        }
    }
}
